<?php

namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use app\api\controller\v1\Common;
use think\Validate;
use app\api\model\User as UserModel;
use app\api\validate\User as UserValidate;
use think\facade\Env;

class User extends Common
{
    protected $params;
    public function __construct(Request $request) {
        //parent::initialize(); //验证token 和 接口有效期
        $data = $request->except(['time', 'token']);
        $validate = new UserValidate();
        $action = $request->action();
        if($action == 'upload_head_img'){
            //$data = $request->param(true);
            $data['user_icon'] = request()->file('user_icon');
        }
        if (!$validate->scene($action)->check($data)) {
            $this->msg(400, $validate->getError());
        }
        //$data = request()->param();    
        //通过验证
        $this->params = $data;
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        echo session('a');
        dump(request()->session());
        return '135';
    }
    
    public function login(){
//        $data = $this->request->param();
//        $validate = new UserValidate();
//        if (!$validate->scene('login')->check($data)) {
//            $this->msg(400, $validate->getError());
//        }
        $data = $this->params;
        /* 检测用户名 */
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], $user_name_type, 1);// 因为是登录 所以要查询是否存在
                $res = UserModel::field('user_id,user_name,user_pwd,user_phone,user_email,user_rtime')->where('user_phone',$data['user_name'])->find();
                break;
            case 'email':
                $this->check_exist($data['user_name'], $user_name_type, 1);// 因为是登录 所以要查询是否存在
                $res = UserModel::field('user_id,user_name,user_pwd,user_phone,user_email,user_rtime')->where('user_email',$data['user_name'])->find();
                break;
            default:
                break;
        }
        
        if($res['user_pwd']!==md5($data['user_pwd'])){
            $this->msg(400,'用户名或者密码错误！');
        }else{
            unset($data['user_pwd']); //删除密码
            $this->msg(200,'登录成功。',$res);
        }
    }
    
    /**
     * 用户注册
     * @return json api返回的JSON数据
     */
    
    public function register(){
//        $data = $this->request->param();
//        $data['user_name'] = $this->request->param('user_name');
//        $data['user_pwd'] = $this->request->param('user_pwd');
//        $data['code'] = $this->request->param('code');
//        $validate = new UserValidate();
//        if (!$validate->scene('register')->check($data)) {
//            $this->msg(400, $validate->getError());
//        }
        $data = $this->params;
//         $data = request()->param();
        /* 验证通过，检查验证码 */
        $this->check_code($data['user_name'],$data['code']);
        
        /* 检查用户名 */
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], $user_name_type, 0);
                $data['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], $user_name_type, 0);
                $data['user_email'] = $data['user_name'];
                break;
            default:
                break;
        }
        /* 将用户信息写入数据库 */
        unset($data['user_name']);
        $data['user_rtime'] = time();
        if(isset($data['user_pwd'])){
            $data['user_pwd'] = md5($data['user_pwd']);
        }
        $userModel = new UserModel();
        $userModel->allowField(true)->save($data);
        if($userModel->user_id){
            $this->msg(200,'用户注册成功');
        }else{
            $this->msg(400,'注册失败！');
        }
    }
    
    /**
     * 用户上传头像
     */
    
    public function upload_head_img(){
        $data = $this->params;
        /* 上传文件，获得路径 */
        $head_img_path = $this->upload_file($data['user_icon'],'head_img');
        /* 存入数据库 */
        $user = UserModel::get($data['user_id']);
        $user->user_icon = $head_img_path;
        $res = $user->save();
        //$res = UserModel::where('user_id',$data['user_id'])->update(['user_icon',$head_img_path]);
        if($res){
            $this->msg(200,'头像上传成功！',$head_img_path);
        }else{
            $this->msg(400,'头像上传失败！');
        }
    }
    
    public function upload_file($file,$type=''){
        $info = $file->move(Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads');
        if($info){
            $path = '/uploads/'.$info->getSaveName();
            /* 裁剪图片 */
            if(!empty($type)){
                $this->image_edit($path,$type);
            }
            return str_replace('\\', '/', $path);
        }else{
            $this->msg(400,$file->getError());
        }
    }
    
    public function image_edit($path,$type) {
        $image = \think\Image::open(Env::get('root_path').'public'.$path);
        switch ($type) {
            case 'head_img':
                $image->thumb(200,200,\think\Image::THUMB_CENTER)->save(Env::get('root_path').'public'.$path);
                break;

            default:
                break;
        }
    }
    
    
    /**
     * 用户修改密码
     * @return json 返回json格式
     */
    public function change_pwd() {
        /* 接收参数 */
        $data = $this->params;
        /* 检测用户名是否存在，存在取出密码 */
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], $user_name_type, 1); //1代表存在
                $where['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], $user_name_type, 1); //1代表存在
                $where['user_email'] = $data['user_name'];
                break;
            default:
                break;
        }
        /* 判断原始密码是否正确，正确则修改密码 */
        $user = UserModel::where($where)->find();
        if($user['user_pwd'] != md5($data['user_rpwd'])){
            $this->msg(400,'原密码错误！');
        }else{
            $user->user_pwd = md5($data['user_pwd']);
            $res = $user->save();
            if($res!==false){
                $this->msg(200,'密码更新成功！');
            }else{
                $this->msg(400,'密码更新失败，请稍后重试！');
            }
        }
    }
    
    /**
     * 找回密码
     * @return json
     */
    
    public function find_pwd(){
        /* 接收参数 */
        $data = $this->params;
        /* 检测验证码 */
        $this->check_code($data['user_name'], $data['code']);
        /* 检测用户名是否存在 */
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], $user_name_type, 1); //1代表存在
                $where['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], $user_name_type, 1); //1代表存在
                $where['user_email'] = $data['user_name'];
                break;
            default:
                break;
        }
        
        $user = UserModel::where($where)->find();
        if(!$user){
            $this->msg(400,'用户不存在！');
        }
        /* 更新密码 */
        $user->user_pwd = md5($data['user_pwd']);
        $res = $user->save();
        if($res!==false){
            $this->msg(200,'密码更新成功！');
        }else{
            $this->msg(400,'密码更新失败，请稍后重试！');
        }
        
        /*  */
        return 'find';
    }
    
    /**
     * 绑定手机号
     */
    public function bind_phone(){
        /* 接收参数 */
        $data = $this->params;
        /* 检查验证码 */
        $this->check_code($data['user_phone'], $data['code']);
        /* 检查数据库是否存在 */
        $info = UserModel::where('user_phone',$data['user_phone'])->find();
        if($info){
            $this->msg(400,'手机号已经存在！');
        }
        /* 修改数据库 */
        $user = UserModel::where('user_id',$data['user_id'])->find();
        $user->user_phone = $data['user_phone'];
        $res = $user->save();
        if($res!==false){
            $this->msg(200,'手机号绑定成功！');
        }else{
            $this->msg(400,'绑定失败，请稍后重试！');
        }
    }
    
    /**
     * 绑定邮箱
     */
    public function bind_email(){
        /* 接收参数 */
        $data = $this->params;
        /* 检查验证码 */
        $this->check_code($data['user_email'], $data['code']);
        /* 检查数据库是否存在 */
        $info = UserModel::where('user_email',$data['user_email'])->find();
        if($info){
            $this->msg(400,'邮箱已经存在！');
        }
        /* 修改数据库 */
        $user = UserModel::where('user_id',$data['user_id'])->find();
        $user->user_email = $data['user_email'];
        $res = $user->save();
        if($res!==false){
            $this->msg(200,'邮箱绑定成功！');
        }else{
            $this->msg(400,'绑定失败，请稍后重试！');
        }
    }
    
    /**
     * 绑定用户手机号或邮箱
     */
    public function bind_user_name() {
         /* 接收参数 */
        $data = $this->params;
        /* 检测用户名是否存在 */
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $where['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $where['user_email'] = $data['user_name'];
                break;
            default:
                break;
        }
        $user = UserModel::where('user_id',$data['user_id'])->find();
        if(!$user){
            $this->msg(400,'用户不存在！');
        }
        /* 检查验证码 */
        $this->check_code($data['user_name'], $data['code']);
        /* 检查数据库是否存在 */
        $res = UserModel::where($where)->find();
        if($res){
            $this->msg(400,'邮箱或手机号已经存在！');
        }
        /* 修改数据库 */
//        $user = UserModel::where('user_id',$data['user_id'])->find();
        //$user->user_email = $data['user_email'];
//        $res = $user->save();
        $res = UserModel::where('user_id',$data['user_id'])->update($where);
        if($res!==false){
            $this->msg(200,'绑定成功！');
        }else{
            $this->msg(400,'绑定失败，请稍后重试！');
        }
    }
    
    public function set_nickname(){
        /* 接收参数 */
        $data = $this->params;
        /* 检测昵称是否存在 */
        $info = UserModel::where('user_nickname',$data['user_nickname'])->find();
        if($info){
            $this->msg(400,'昵称已被占用！');
        }
        /* 更新数据库 */
        $user = UserModel::where('user_id',$data['user_id'])->find();
        $user->user_nickname = $data['user_nickname'];
        $res = $user->save();
        if($res!==false){
            $this->msg(200,'昵称修改成功');
        }else{
            $this->msg(400,'昵称更新失败！');
        }
    }

    


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
